<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    :modal="false"
    top="1"
    style="padding-top:60px"
    :close-on-click-modal="false"
    width="980px"
    class="single-prods-select-dialog"
  >
    <el-form
      :inline="true"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.itemName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.itemName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('product.singleProductBar')">
        <el-input
          v-model="barCode"
          :placeholder="$t('product.singleProductBar')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t("order.query") }}
        </div>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t("shop.resetMap") }}
        </div>
      </el-form-item>
    </el-form>
    <div class="main-container">
      <div class="table-con prods-select-body">
        <el-table
          ref="prodTableRef"
          v-loading="dataListLoading"
          :data="dataList"
          :header-cell-style="{height: '42px', background: '#F6F7FA', color:'#666666','font-weight': '500'}"
          :cell-style="{height: '64px', padding: '8px 0', color:'#000'}"
          style="width: 100%;"
          height="530"
          @selection-change="selectChangeHandle"
        >
          <el-table-column
            v-if="isSingle"
            width="50"
            align="center"
          >
            <template #default="scope">
              <div>
                <el-radio
                  v-model="singleSelectProdId"
                  :label="scope.row.retailProdId"
                  @change="getSelectProdRow(scope.row)"
                >
&nbsp;
                </el-radio>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!isSingle"
            type="selection"
            header-align="center"
            align="center"
            width="50"
          />
          <el-table-column
            width="100"
            :label="$t('product.singleProdPic')"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <ImgShow :src="scope.row.pic" />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="name"
            :label="$t('product.itemName')"
          >
            <template #default="scope">
              <div class="table-cell-text">
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="spec"
            :label="$t('product.singleProdSpe')"
          />
          <el-table-column
            prop="costPrice"
            :label="$t('product.singleProd')"
          />
          <el-table-column
            prop="stocks"
            :label="$t('product.singleProdInve')"
          />
          <el-table-column
            prop="barCode"
            :label="$t('product.singleProductBar')"
          />
          <el-table-column
            prop="categoryName"
            :label="$t('product.singleProdClas')"
          >
            <template #default="scope">
              <div class="table-cell-text">
                {{ scope.row.categoryName }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="submitProds()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils'

const emit = defineEmits(['refreshSelectSingleProds'])
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  dataUrl: {
    default: '/shop/retailProd/page',
    type: String
  }
})

const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)

const categoryTreeProps = reactive({
  value: 'categoryId',
  label: 'categoryName'
})

onActivated(() => {
  getDataList()
})

// 获取数据列表
const visible = ref(false)
let selectProds = []
const singleSelectProdId = ref(0)
const dataListLoading = ref(false)
let dataListSelections = []
let oriSelectData = [] // 选择的原来的数据
const init = (selectProdsPar) => {
  singleSelectProdId.value = 0
  selectProds = selectProdsPar
  visible.value = true
  dataListLoading.value = true
  if (selectProds) {
    selectProds.forEach(row => {
      dataListSelections.push(row)
      oriSelectData.push(row)
    })
  }
  getDataList()
  getCategoryList()
}

const categoryList = ref([])
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}

const dataList = ref([])
const prodName = ref('')
const barCode = ref('')
let shopCategoryId = null
const prodTableRef = ref(null)
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          name: prodName.value || null,
          categoryId: shopCategoryId || null,
          barCode: barCode.value || null
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    totalPage.value = data.total
    dataListLoading.value = false
    if (selectProds) {
      nextTick(() => {
        selectProds.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.retailProdId === row.retailProdId)
          prodTableRef.value.toggleRowSelection(dataList.value[index])
        })
      })
    }
  })
}
// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}
// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}
// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections = [row]
}
// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = selection.findIndex((selectedProd) => {
      if (!selectedProd) {
        return false
      }
      return selectedProd.retailProdId === tableItem.retailProdId
    })
    const dataSelectedProdIndex = dataListSelections.findIndex((dataSelectedProd) => dataSelectedProd.retailProdId === tableItem.retailProdId)
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.splice(dataSelectedProdIndex, 1)
    }
  })
}
/**
 * 获取分类id
 */
const handleChange = (val) => {
  shopCategoryId = val[val.length - 1]
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}
/**
 * 清空搜索条件
 */
const selectedCategory = ref([])
const clean = () => {
  prodName.value = ''
  barCode.value = ''
  shopCategoryId = null
  selectedCategory.value = idList(categoryList.value, shopCategoryId, 'categoryId', 'children').reverse()
}
// 确定事件
const submitProds = () => {
  dataListSelections.forEach(item => {
    if (oriSelectData.length) {
      const oriProd = oriSelectData.find((oriItem) => oriItem.retailProdId === item.retailProdId)
      if (oriProd) {
        item.retailNums = oriProd.retailNums
        item.total = oriProd.total
      } else {
        item.retailNums = 1
        item.total = item.costPrice
      }
    } else {
      item.retailNums = 1
      item.total = item.costPrice
    }
  })
  emit('refreshSelectSingleProds', dataListSelections)
  dataListSelections = []
  oriSelectData = []
  visible.value = false
}

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
.single-prods-select-dialog {
  .main-container {
    padding: 0;
    .table-con.prods-select-body{
      padding-bottom: 0;
      height: 550px;
      overflow: auto;
    }
  }
  :deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 6px;
    height: 439px;
    background: #F7F8FA;
    opacity: 1;
    border-radius: 4px;
  }
  // 滚动条的滑块
  :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    width: 6px;
    height: 150px;
    background: #E9ECF3;
    opacity: 1;
    border-radius: 4px;
  }
}

</style>
